import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, message, Input, Upload, Row, Col, Select, DatePicker, Form, Icon, TreeSelect, Tabs, InputNumber, Radio, Video, Button } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';

import check from '../../utils/checkLib';

moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;

let editor = null;

function toString(str, type) {
  if (typeof str !== 'undefined' && str !== null) {
    return str.toString();
  }
  if (type === 'SELECT') return undefined;
  return '';
}

let uuid = 0;

class BuySiteAndCityDetailModal extends Component {


  constructor(props) {
    super(props);
    this.state = {
    	selectValue: null
    };
  }

  handleSubmit() {
    const p = this;
    const { form, dispatch, modalValues } = this.props;
    form.validateFields((err, fieldsValue) => {
    	if (p.props.addUpdateStatus==1 && Object.keys(err).length>1) {
    		return;
    	} else if(p.props.addUpdateStatus==0) {
    		if (err) { return; }
    	}
    	const siteArr = JSON.stringify(fieldsValue.siteArr);
	    if (modalValues && modalValues.data) {
	    	console.log(fieldsValue);
	      dispatch({
	        type: 'purchase/updateBuySiteAndCity',
	        payload: { ...fieldsValue, id: modalValues.data.id },
	        cb() { p.closeModal(); },
	      });
	    } else {
	      dispatch({
	        type: 'purchase/addBuySiteAndCity',
	        payload: { siteArr } ,
	        cb() { p.closeModal(); },
	      });
	    }
    });
  }

  closeModal() {
    const { form, close } = this.props;
    form.resetFields();
    uuid = 0;
    this.setState({
    	selectValue: null
    });
    close();
  }

	addNewModel() {
		const p = this;
		const { form } = this.props;
		const siteKeys = form.getFieldValue('siteKeys');
		siteKeys.push(++uuid);

		const siteOneKeys = form.getFieldValue('siteOneKeys');
		siteOneKeys.push([0]);

    form.setFieldsValue({
      siteKeys: siteKeys,
      siteOneKeys: siteOneKeys
    });
	}

	deleteNewModel(k) {
		const { form } = this.props;
    let siteArr = form.getFieldValue('siteArr');
    siteArr.splice(k, 1);

    let siteKeys = form.getFieldValue('siteKeys');
    let siteKeysNew = [];
    for(let i=0; i<siteKeys.length - 1; i++) {
    		siteKeysNew.push(i);
    }

    form.setFieldsValue({
      siteKeys: siteKeysNew,
      siteArr: siteArr
    });
    --uuid;
	}

	addNewModelOne(key, keyOne) {
		const { form } = this.props;
		const siteOneKeys = form.getFieldValue('siteOneKeys');
		let length = siteOneKeys[key].length;
		siteOneKeys[key].push(length);
    form.setFieldsValue({
      siteOneKeys: siteOneKeys,
    });
	}

	deleteNewModelOne(key, keyOne) {
		const { form } = this.props;
		let siteArr = form.getFieldValue('siteArr');
    siteArr[key]['siteArrOne'].splice(keyOne, 1);
    let siteOneKeys = form.getFieldValue('siteOneKeys');
    let length = siteOneKeys[key].length - 1;
    let newArr = [];
    for(let i=0; i<length; i++) {
    		newArr.push(i);
    }
    siteOneKeys[key] = newArr;

    form.setFieldsValue({
      siteOneKeys: siteOneKeys,
      siteArr: siteArr
    });

	}

  render() {
    const p = this;
    const { form, visible, itemBuySiteNoPagingList = [], modalValues = {} } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    // 详情数据
    const productData = (modalValues && modalValues.data) || {};

    const modalProps = {
      visible,
      width: 1200,
      wrapClassName: 'modalStyle',
      title: (p.props.addUpdateStatus==1) ? '修改' : '添加',
      maskClosable: false,
      closable: true,
      onOk() {
        p.handleSubmit();
      },
      onCancel() {
        p.closeModal();
      },
    };

    const formItemLayout = {
      labelCol: { span: 11 },
      wrapperCol: { span: 13 },
    };

		function obtainSelectValue(value) {
			p.setState({
				selectValue: value
			});
		}

		getFieldDecorator('siteKeys', { initialValue: [0] });
    const siteKeys = getFieldValue('siteKeys');

    getFieldDecorator('siteOneKeys', { initialValue: [[0]] });
    const siteOneKeys = getFieldValue('siteOneKeys');

		getFieldDecorator('siteArr', { initialValue: [{}] });
		const siteArr = getFieldValue('siteArr');

    const formItems = siteKeys.map((key) => {
    	return (
    		<div>
	    		<Row>
            <Col span={7}>
              <FormItem
                label="选择站点"
                {...formItemLayout}
              >
                {getFieldDecorator(`siteArr[${key}].buySite`, {
                	initialValue: p.state.selectValue || undefined,
                  rules: [{ required: true, message: '请输入站点' }],
                })(
                  <Select
                    allowClear
                    placeholder="请输入站点"
                    showSearch
                    onChange={obtainSelectValue}
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  >
                    {itemBuySiteNoPagingList && itemBuySiteNoPagingList.map(item => <Option key={item.buySite}>{item.buySite}</Option>)}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={7}>
              <FormItem
                label="城市"
                {...formItemLayout}
              >
                {getFieldDecorator(`siteArr[${key}].buyCity`, {
                  rules: [{ required: true, message: '请输入站点' }],
                })(
                  <Select placeholder="请选择" allowClear>
                    <Option key="波特兰" value="波特兰">波特兰</Option>
                    <Option key="西雅图" value="西雅图">西雅图</Option>
                    <Option key="洛杉矶" value="洛杉矶">洛杉矶</Option>
                    <Option key="纽约"   value="纽约">纽约</Option>
                  </Select>,
                )}
              </FormItem>
            </Col>
            {
	            	key > 0  ?
	            	<Col style={{ textAlign:"right" }}>
			            	<Icon type="minus-square" style={{ fontSize: 32, color: '#08c' }} onClick={p.deleteNewModel.bind(p, key)}/>
			        	</Col> :
			        	<Col style={{ textAlign:"right" }}>
	              	<Icon type="plus-square" style={{ fontSize: 32, color: '#08c' }} onClick={p.addNewModel.bind(p)}/>
	            	</Col>
	          }
	        </Row>
	        <Row>
          {
            siteOneKeys[key].map((keyOne) => {
            			return (
									<div>
										<Row>
					            <Col span={7}>
					              <FormItem
					                label="店铺位置"
					                {...formItemLayout}
					              >
					                {getFieldDecorator(`siteArr[${key}].siteArrOne[${keyOne}].shopSite`, {
					                  rules: [{ required: true,message: '请输入店铺位置名称' }],
					                })(
					                  <Input placeholder="请输入店铺位置名称" />,
					                )}
					              </FormItem>
					            </Col>
					            <Col span={7}>
					              <FormItem
					                label="税率(%)"
					                {...formItemLayout}
					              >
					                {getFieldDecorator(`siteArr[${key}].siteArrOne[${keyOne}].buyTax`, {
                            initialValue: 0,
					                  rules: [{ required: true, message: '请输入税率' }],
					                })(
					                   <InputNumber step={1} min={0}  max={100} placeholder="请填写税率"/>,
					                )}
					              </FormItem>
					            </Col>
					            { keyOne > 0 ?
						          	<Icon type="minus-square" style={{ fontSize: 32, color: '#08c', marginLeft:10}} onClick={p.deleteNewModelOne.bind(p, key, keyOne)}/> :
						          	<Icon type="plus-square" style={{ fontSize: 32, color: '#08c', marginLeft:10}} onClick={p.addNewModelOne.bind(p, key, keyOne)}/>
					            }
					          </Row>
									</div>
								)
            	})
            }
          </Row>
          <Row>
             <Col span={7}>
              <FormItem
                label="状态"
                {...formItemLayout}
              >
                {getFieldDecorator(`siteArr[${key}].status`, {
                  initialValue: toString(0, 'SELECT'),
                  rules: [{ required: false, message: '选择此站点明细的状态' }],
                })(
                  <Select placeholder="请选择" allowClear>
                    <Option key="0" value="0">正常</Option>
                    <Option key="1" value="1">停用</Option>
                  </Select>,
                )}
              </FormItem>
            </Col>
          </Row>
          {
          	key != siteKeys.length-1 ? <Row className='operBtn'></Row> : ''
          }
        </div>
    	)
    });

    return (
      <Modal
        {...modalProps}
      >
          <Form onSubmit={this.handleSubmit.bind(this)} >
            {p.props.addUpdateStatus==1 ?
            	<div>
	              <Row>
	                <Col span={7}>
	                  <FormItem
	                    label="选择站点"
	                    {...formItemLayout}
	                  >
	                    {getFieldDecorator(`buySite`, {
	                      initialValue: toString(productData.buySite, 'SELECT'),
	                      rules: [{ required: true, message: '请输入站点' }],
	                    })(
	                      <Select
	                        allowClear
	                        placeholder="请输入站点"
	                        showSearch
	                        optionFilterProp="children"
	                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
	                      >
	                        {itemBuySiteNoPagingList && itemBuySiteNoPagingList.map(item => <Option key={item.buySite}>{item.buySite}</Option>)}
	                      </Select>,
	                    )}
	                  </FormItem>
	                </Col>
	                <Col span={7}>
	                  <FormItem
	                    label="城市"
	                    {...formItemLayout}
	                  >
	                    {getFieldDecorator(`buyCity`, {
	                      initialValue: productData.buyCity,
	                      rules: [{ required: true, message: '请输入站点' }],
	                    })(
	                      <Select placeholder="请选择" allowClear>
	                        <Option key="波特兰" value="波特兰">波特兰</Option>
	                        <Option key="西雅图" value="西雅图">西雅图</Option>
	                        <Option key="洛杉矶" value="洛杉矶">洛杉矶</Option>
	                        <Option key="纽约"   value="纽约">纽约</Option>
	                      </Select>,
	                    )}
	                  </FormItem>
	                </Col>
	              </Row>
	              <Row>
	                <Col span={7}>
	                  <FormItem
	                    label="店铺位置"
	                    {...formItemLayout}
	                  >
	                    {getFieldDecorator(`shopSite`, {
	                      initialValue: toString(productData.shopSite),
	                      rules: [{ required: true,message: '请输入店铺位置名称' }],
	                    })(
	                      <Input placeholder="请输入店铺位置名称" />,
	                    )}
	                  </FormItem>
	                </Col>
	                <Col span={7}>
	                  <FormItem
	                    label="税率(%)"
	                    {...formItemLayout}
	                  >
	                    {getFieldDecorator(`buyTax`, {
	                      initialValue: toString(productData.buyTax),
	                      rules: [{ required: true, message: '请输入税率' }],
	                    })(
	                       <InputNumber step={1} min={0}  max={100} placeholder="请填写税率"/>,
	                    )}
	                  </FormItem>
	                </Col>
	              </Row>
	              <Row>
	                 <Col span={7}>
	                  <FormItem
	                    label="状态"
	                    {...formItemLayout}
	                  >
	                    {getFieldDecorator(`status`, {
	                      initialValue: toString(productData.status, 'SELECT'),
	                      rules: [{ required: false, message: '选择此站点明细的状态' }],
	                    })(
	                      <Select placeholder="请选择" allowClear>
	                        <Option key="0" value="0">正常</Option>
	                        <Option key="1" value="1">停用</Option>
	                      </Select>,
	                    )}
	                  </FormItem>
	                </Col>
	              </Row>
              </div> : formItems
            }
          </Form>
      </Modal>
    );
  }
}


export default Form.create()(BuySiteAndCityDetailModal);
